package project.mafia.network;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;

public class Server extends Thread{
	private final int SERVER_PORT = 7000;
	private boolean running;
	private	ServerSocket serverSock;
	private LinkedList<ConnectionForServer> connectionList;
	private LinkedList<Packet> packetQueue;
	public Server() throws IOException{
		serverSock = new ServerSocket(SERVER_PORT);
		connectionList = new LinkedList<ConnectionForServer>();
		packetQueue = new LinkedList<Packet>();
	}
	
	public void addPacket(Packet p){
		packetQueue.add(p);
	}
	
	public Packet getPacket(){
		if(packetQueue.size()>0){
			Packet p = packetQueue.get(0);
			packetQueue.remove(0);
			return p;
		}
		return null;
	}
	
	public void stopServerThread(){
		running = false;
	}
	
	public synchronized void broadcast(Packet packet){
		for(int i = connectionList.size() - 1; i >= 0; i--){
			ConnectionForServer c = connectionList.get(i);
			if(c.isRunning()){
				try {
					c.sendPacket(packet);
				} catch (IOException e) {}
			}else{
				connectionList.remove(c);
			}	
		}
	}
	
	public void run(){
		running = true;
		while(running){
			try {
				System.out.println("Waiting Connection...");
				Socket socket = serverSock.accept();
				ObjectInputStream oistream = new ObjectInputStream(socket.getInputStream());
				Packet receive = (Packet)oistream.readObject();
				System.out.println("Someone Connected...");
				switch(receive.getType()){
				case 0: // Make Connection
					System.out.println("Making Connection...");
					ConnectionForServer c = new ConnectionForServer(this,socket,oistream);
					c.setDaemon(true);
					c.start();
					connectionList.add(c);
					System.out.println("Connection added on list...");
					break;
				default:
					System.out.println("Unexpected packet type...");
					break;
						
				}
				
			} catch (IOException | ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
	}
}
